<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="70px" :rules="rules">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="form.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-switch
          v-model="form.state"
          active-text="启用"
          inactive-text="禁用"
        ></el-switch>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="js" name="">
import { ref, defineEmits, defineProps, watch } from 'vue'
import { addUserAPI, updateUserAPI } from '@/apis/user'
import { ElMessage } from 'element-plus'
import JSEncrypt from 'jsencrypt';

//公钥
const publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCW0GPS4xex6X3hb34aHREHS4TpWlr1bdYea7Db6k5U6gH06YekUGgsvrtBu7xtVz6nEThfp2RoPkTUoEdAQNRC6RMU9hjRq/96Zfcy+LM884Ip9W/YNBHHG3/tT7Hv8sDr3XCvD3R5KNHR1VjuzXqpaHfUVxZJREMZB30HKBhSPQIDAQAB';

//加密密码的函数
//使用公钥对密码进行加密
const encryptPassword = (password) => {
  const crypt = new JSEncrypt();
  crypt.setPublicKey(publicKey);
  return crypt.encrypt(password);
}


const props = defineProps({
    dialogTitle: {
        type: String,
        default: '',
        required: true
    },
    dialogTableValue: {
        type: Object,
        default: () => {}
    }
})

const emits = defineEmits(['update:modelValue', 'initUserList'])
const formRef = ref(null)
const form = ref({
  username: '',
  phoneNumber: '',
  state: false, // 假设状态为布尔值，启用为true，禁用为false
  gender: '',
  password: ''
})
const rules = ref({
    username: [
        {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
        }
    ],
    phoneNumber: [
        {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
        }
    ],
    gender: [
        {
            required: true,
            message: '请输入性别',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
        }
    ]
})


const handleClose = () => {
    emits('update:modelValue',false)
}

const handleSave = async () => {
    await formRef.value.validate(async (valid) => {
      if (valid) {

        //在提交之前加密密码
        //加密密码
        form.value.password = encryptPassword(form.value.password);

            const res = props.dialogTitle === '添加用户'
                ? await addUserAPI(form.value)
                : await updateUserAPI(form.value);

            if (res.data.code === 1) {
                emits('initUserList');
                ElMessage({
                    message: "保存成功",
                    type: 'success'
                });
                handleClose();
            } else {
                // 显示错误信息
              ElMessage({
                    message:res.data.msg,
                    type: 'error'
                });
                return false;
            }
        }
    });
}


watch(
    () => props.dialogTableValue,
    () => {
        form.value = props.dialogTableValue
    },
    {deep: true,immediate: true}
)
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
 </style>